; panic.asm
; Handle serious error

	.export panic
	.export brkhdl

	.include "string.inc"
	.include "vicrom.inc"

	.segment "DATA"

accu:		.byte 0
xreg:		.byte 0
yreg:		.byte 0
sp:			.byte 0

hdist:		.byte 3

	.segment "RODATA"

msgbuf:		.byte emsize, acpos 
errormsg:	.byte "?fatal error", 13, 13
	acpos = * - errormsg + 2
			.byte "a=00 x=00 y=00 sp=00", 13
			.byte "stack:", 13, 0
	emsize = * - errormsg
			.byte 0

	.segment "CODE"

brkhdl:		pla
			sta yreg 
			pla
			sta xreg
			pla
			sta accu
			pla
			jmp panic2
			
outbyte:	jsr sputhexb
			clc
			lda msgbuf+1
			adc hdist
			sta msgbuf+1
			rts
			
panic:		sei
			sta accu
			stx xreg
			sty yreg
panic2:		lda #<msgbuf
			ldx #>msgbuf
			jsr ssetbuf		; write regs to message
			lda accu
			ldy #3
			sty hdist
			jsr outbyte
			lda xreg
			jsr outbyte
			lda yreg
			inc hdist
			jsr outbyte
			tsx
			stx sp
			txa
			jsr outbyte
			jsr CINT1		; I/O Reset
			lda #$6E		; all blue
			sta $900F
			lda #1			; white text
			sta $0286
			lda #<errormsg	; print error title.
			ldy #>errormsg
			jsr STROUT
			jsr sclear		; dump stack
@prstklp:	ldx sp
			inx	
			beq @done
			stx sp
			lda $0100, x
			jsr sputhexb
			lda #32
			jsr saddch
			jmp @prstklp
@done:		lda #13
			jsr saddch
			lda #0
			jsr saddch
			lda #<errormsg	; print stack.
			ldy #>errormsg
			jsr STROUT

			jmp READY
